package com.example.mobile1921605031dsd0522homework;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

public
class MainActivity extends AppCompatActivity {

    private WebView wvMainLogin;

    @Override
    protected
    void onCreate(Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.activity_main );
        initView ( );
        wvMainLogin.loadUrl ( "file:////android_asset/login.html" );
        wvMainLogin.setWebViewClient ( new WebViewClient ( ) {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public
            boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                //   return super.shouldOverrideUrlLoading(view, request);
                view.loadUrl ( request.getUrl ( ).toString ( ) );
                return true;
            }
        } );
        WebSettings webSettings = wvMainLogin.getSettings ( );
        webSettings.setJavaScriptEnabled ( true );
        webSettings.setDomStorageEnabled ( true );
        webSettings.setDefaultTextEncodingName ( "UTF-8" );
        wvMainLogin.addJavascriptInterface ( new WebViewJsInterface ( this ), "myObj" );
    }

    private
    void initView() {
        wvMainLogin = (WebView) findViewById ( R.id.wvMainLogin );
    }

    class WebViewJsInterface {
        Context context;

        public
        WebViewJsInterface(Context context) {
            this.context = context;
        }


        @JavascriptInterface
        public
        void login(String name, String password) {
            if (name.equals ( "admin" ) && password.equals ( "123456" )) {
                startActivity ( new Intent ( MainActivity.this, ContentActivity.class ) );
            } else {
                Toast.makeText ( context, "登陆失败", Toast.LENGTH_LONG ).show ( );
            }
        }
    }
}
